import { Form, Input, Space } from "antd"
import { FC } from "react"

import { SFormItem } from "@/components/common"
import { Toast } from "@/components/messages"
import { useLocale } from "@/locales"
import { onlyNumberAndHyphen, onlyPositiveNumber } from "@/utils/validate"

const MinMax: FC<{
	fields: [minField: string, maxField: string]
	placeholder?: [placeholderMin: string, placeholderMax: string]
	label?: string
	allowValidate?: boolean
	isAllowNegative?: boolean
	onChangeMin?: (value: string) => void
	onChangeMax?: (value: string) => void
	normalize?: ((value: any, prevValue: any, allValues: any) => any) | undefined
}> = props => {
	const { formatMessage } = useLocale()

	const onNotAllowMin = (value: string) => {
		props.onChangeMin && props.onChangeMin(value)
	}

	const onNotAllowMax = (value: string) => {
		props.onChangeMax && props.onChangeMax(value)
	}
	const form = Form.useFormInstance()
	const minValue = Form.useWatch(props.fields[0], form)
	const maxValue = Form.useWatch(props.fields[1], form)
	const validMinMax = () => {
		if (+minValue > +maxValue) {
			Toast.warning(`${props.label}:` + formatMessage({ id: "tips.minMax" }))
			form.setFieldValue(props.fields[1], undefined)
		}
	}
	const defaultNormalize = (value: string) => value.replaceAll(" ", "") || undefined

	return (
		<div className="flxR aiC">
			<Space.Compact>
				<SFormItem label={props.label} name={props.fields[0]} normalize={props.normalize || defaultNormalize}>
					<Input
						placeholder={props.placeholder ? props.placeholder[0] : formatMessage({ id: "tips.min" })}
						onChange={e =>
							props.allowValidate &&
							(props.isAllowNegative ? onlyNumberAndHyphen(e, onNotAllowMin) : onlyPositiveNumber(e, onNotAllowMin))
						}
						onBlur={() => validMinMax()}
						autoComplete="off"
					/>
				</SFormItem>
				<SFormItem>
					<Input
						style={{
							width: 30,
							borderLeft: 0,
							borderRight: 0,
							pointerEvents: "none"
						}}
						placeholder="~"
						disabled
					/>
				</SFormItem>
				<SFormItem name={props.fields[1]} normalize={props.normalize || defaultNormalize}>
					<Input
						placeholder={props.placeholder ? props.placeholder[1] : formatMessage({ id: "tips.max" })}
						onChange={e =>
							props.allowValidate &&
							(props.isAllowNegative ? onlyNumberAndHyphen(e, onNotAllowMax) : onlyPositiveNumber(e, onNotAllowMax))
						}
						onBlur={() => validMinMax()}
						autoComplete="off"
					/>
				</SFormItem>
			</Space.Compact>
		</div>
	)
}
export default MinMax
